package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.domain.User;
import com.qf.util.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author Administrator
 * @version v1.0
 * @date 2022/4/18
 */
public class UserDapImpl implements UserDao {
    private QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDatasource());
    @Override
    public long selectCountByUsername(String username) {
        String sql = "SELECT COUNT(`id`) FROM `tb_user` WHERE `username` = ?;";
        try {
           return   (Long)queryRunner.query(sql, new ScalarHandler(),username);
        } catch (SQLException e) {
           throw new RuntimeException(e);
        }

    }

    @Override
    public int insert(User user) {
        String sql = "insert into tb_user values(null ,?,md5(?),?,?,?,?,?)";
        Object[] params ={user.getUsername(), user.getPassword(), user.getEmail(), user.getGender(), user.getFlag(), 1, ""};
        try {
            return queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public User selectByUsernameAndPassword(String username, String password) {
        String sql = "SELECT `id`,`username`,`password`,`email`,`gender`,`flag`,`role`,`code` FROM `tb_user` WHERE `username` = ? and password =md5(?) and role = 1;";
        try {
            return   queryRunner.query(sql,new BeanHandler<>(User.class),username,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<User> selectUsers() {
        String sql = "SELECT `id`,`username`,`password`,`email`,`gender`,`flag`,`role`,`code` FROM `tb_user` WHERE  role = 1;";
        try {
            return   queryRunner.query(sql,new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteUser(int id) {
        String sql = "delete from tb_user WHERE  id = ?;";
        try {
             queryRunner.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<User> selectUsersAny(String toString, List<Object> params) {
        String sql = "SELECT `id`,`username`,`password`,`email`,`gender`,`flag`,`role`,`code` FROM `tb_user` "+toString;
        try {
            return   queryRunner.query(sql,new BeanListHandler<>(User.class),params.toArray());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


}
